package com.java.lb.impl;

import com.java.lb.LoadBalance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Random;

@Component
public class RandomLoadBalance implements LoadBalance {

    @Autowired
    private DiscoveryClient discoveryClient;

    private List<ServiceInstance> instances = null;

    private Random random = new Random();

    @PostConstruct
    public void init() {
        instances = discoveryClient.getInstances("moon-teacher");
    }

    @Override
    public String getServerIp() {
        int i = random.nextInt(instances.size());
        ServiceInstance service = instances.get(i);
        return service.getUri().toString();
    }

}
